package com.module.user.ui.downCloudData

import android.os.CountDownTimer
import android.util.Base64
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.CloudDownDataModel
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.ServerHealthTypeDataModel
import com.common.app.data.bean.ServerSseDataModel
import com.common.app.data.bean.user.LoginBean
import com.common.app.helper.RouterHelper
import com.common.app.helper.UserHelper
import com.common.app.utls.BrotliCompressionEx
import com.common.app.utls.Constants
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.TimeUtils
import com.common.app.utls.report.ReportEventManager
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.isEmpty
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.postDelay
import com.common.base.app.extras.setText
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.utils.JsonUtils
import com.common.base.utils.SoftInputUtils
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.StatusBarUtils
import com.module.ble.data.bean.CusUnifyData
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserHeartRate
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.db.table.UserSportRecord
import com.module.ble.db.table.UserStepsRelatedRecord
import com.module.ble.repo.BloodOxygenRepo
import com.module.ble.repo.BodyTemperatureRepo
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.repo.SportRecordRepo
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.utils.AizoSDKUtil.bloodOxygenMultiAdd2DB
import com.module.ble.utils.AizoSDKUtil.bodyTempMultiAdd2DB
import com.module.ble.utils.AizoSDKUtil.heartRateMultiAdd2DB
import com.module.ble.utils.AizoSDKUtil.sleepMultiAdd2DB
import com.module.ble.utils.CloudDataDecompressionWorker
import com.module.ble.utils.CommonCusHealthType
import com.module.ble.utils.ServerHealthDataModelType
import com.module.user.R
import com.module.user.databinding.UserActivityRingDataDownloadBinding

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/07/25
 * <p>
 * 描述：下载云端数据页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_DOWN_CLOUD_DATA_ACTIVITY)
class DownCloudDataActivity :
    AppActivity<UserActivityRingDataDownloadBinding, DownCloudDataViewModel>(),
    View.OnClickListener {

    override fun getViewModel() = DownCloudDataViewModel::class.java

    override fun getViewContentBinding() =
        UserActivityRingDataDownloadBinding.inflate(layoutInflater)

    override fun isStatusBarTranslate(): Boolean = true
    override fun isShowToolBar(): Boolean = false

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var commonMessageRelayModel: CommonMessageRelayModel? = null

    private var mBtnCountDownTimer: CountDownTimer? = null

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle("")
        headTitleUtils.setLineStyle(10)
    }

    override fun lazyInitData() {
        super.lazyInitData()
        mViewModel.reconnectSse()//下载

    }


    override fun initEvents() {
        super.initEvents()

        SpUtilsManagement.putInt(KeyPre.KEY_DOWN_CLOUD_DATA_PROGRESS, 0)
        mViewModel._sseData.observe(this) { sseDataIt ->
//            Log.e("SSE", "_sseData: $sseDataIt")
            JsonUtils.fromJson(sseDataIt, ServerSseDataModel::class.java)?.apply {

                (100 <= this.progress ).yes {
                    mViewModel.stopSse()
                }

                this.data.isNullOrEmpty().no {
//                    // 遍历每条数据进行解码和解压
//                    for (cloudData in this.data!!) {
//                        try {
//                            // 检查data字段是否为空
//                            if (!cloudData.data.isNullOrEmpty()) {
//                                // 先将Base64字符串解码回字节数组
//                                val decodedBytes = Base64.decode(cloudData.data, Base64.DEFAULT)
//                                // 然后解压缩
//                                BrotliCompressionEx.decompressToString(decodedBytes).let { dataStrIt ->
//                                    Log.e("SSE", "_sseData----decompressedJson: $dataStrIt")
//                                    doOnIOThread {
//                                        val list: List<CloudDownDataModel> = JsonUtils.fromJsonList(dataStrIt)
//                                        parseClassData(cloudData.type, list)
//                                    }
//                                }
//                            }
//                        } catch (e: Exception) {
//                            Log.e(TAG, "处理数据 ID: ${cloudData.id} 时发生错误: ${e.message}", e)
//                            // 解压失败的数据不添加到删除列表，保留在数据库中
//                        }
//                    }

                    this.data?.forEach {//给到当前数据绑定用户
                        it.userId = UserHelper.getUserDbName()
//                        if (it.type=="sleep"){//数据测试
//                            Log.e("SSE", "sleep_sseData: ${it.data}")
//                        }
                    }

                    ReportEventManager.saveCloudDownData(this.data)
                }


                // 将0-100%的进度映射到0-90%，使用更精确的计算
                val mappedProgress = (progress * 90 / 100)
                setTvProgressUi(mappedProgress)
                (mappedProgress >= 90).yes {
                    if (mBtnCountDownTimer != null) return@yes
                    createCountDownTimer(progress= mappedProgress)
                }
            }
        }


//        mViewContentBinding..setOnClickListener(onClick = this)
    }


    override fun onClick(v: View?) {
        when (v) {
        }
    }

    override fun onDestroy() {
        mViewModel.stopSse()
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer = null
        super.onDestroy()
    }

    private fun setTvProgressUi(progress: Int) {
        val oldProgress = mViewContentBinding.rpdProgress.progress
//        mViewContentBinding.rpdProgress.setProgressWithAnimation(oldProgress, mappedProgress)
        if(progress > 100) return
        mViewContentBinding.rpdProgress.progress = progress
        mViewContentBinding.tvProgress.text =
            String.format("%d%s", progress, getString(R.string.common_bfb_unit))
    }

    private fun createCountDownTimer(time:Int = 10,progress: Int) {
        val rb = (100-progress)/time
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer = null
        mBtnCountDownTimer = object : CountDownTimer(time * 1000L, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
//                Log.e("mBtnCountDownTimer", "onTick: ${millisUntilFinished/1000}")
                setTvProgressUi((90 + (10-(millisUntilFinished/1000))*rb).toInt())
            }

            override fun onFinish() {
                setTvProgressUi(100)
                Log.e("mBtnCountDownTimer", "onFinish()")
                SpUtilsManagement.putInt(KeyPre.KEY_DOWN_CLOUD_DATA_PROGRESS, 1)
                postDelay(500) {
                    RouterHelper.navigationPostcard(RouterHub.ROUTER_MAIN_ACTIVITY)
                        .withParcelable(KeyBundle.BUNDLE_KEY, commonMessageRelayModel).navigation()
                        .run {
                            ((Constants.userBean?.height?:0) <=0).yes {
                                RouterHelper.navigation(RouterHub.ROUTER_COM_PER_INFO_ACTIVITY)
                            }
                            finish()
                        }
                }

            }
        }
        mBtnCountDownTimer?.start()
    }

    fun parseClassData(dataType: String?, mData: List<CloudDownDataModel>) {
        Log.e("SSE", "_sseData----parseClassData: $mData")
        val allData by lazy { arrayListOf<CusUnifyData>() }
        when (dataType) {
            ServerHealthDataModelType.HEARTRATE.value -> {
                val hrData = arrayListOf<UserHeartRate>()
                mData.forEach {
                    JsonUtils.fromJson(it.value ?: "", UserHeartRate::class.java)?.let { beanIt ->
                        beanIt.sysStat = 1
                        hrData.add(beanIt)
                    }
                }
                heartRateMultiAdd2DB(hrData)
            }
            ServerHealthDataModelType.BLOODOXYGEN.value -> {
                val oxyData = arrayListOf<UserBloodOxygen>()
                mData.forEach {
                    JsonUtils.fromJson(it.value ?: "", UserBloodOxygen::class.java)?.let { beanIt ->
                        beanIt.sysStat = 1
                        oxyData.add(beanIt)
                    }
                }
                bloodOxygenMultiAdd2DB(oxyData)
            }
            ServerHealthDataModelType.BODYTEMP.value -> {
                val tmpData = arrayListOf<UserBodyTemperature>()
                mData.forEach {
                    JsonUtils.fromJson(it.value ?: "", UserBodyTemperature::class.java)
                        ?.let { beanIt ->
                            beanIt.sysStat = 1
                            tmpData.add(beanIt)
                        }
                }
                bodyTempMultiAdd2DB(tmpData)
            }
            ServerHealthDataModelType.STEPS.value -> {
                val stepsData = arrayListOf<UserStepsRelatedRecord>()
                mData.forEach {
                    JsonUtils.fromJson(it.value ?: "", UserStepsRelatedRecord::class.java)
                        ?.let { beanIt ->
                            beanIt.sysStat = 1
                            stepsData.add(beanIt)
                        }
                }
                UserStepsRelatedRecordRepo.instance.insertDistinct(stepsData)
            }
            ServerHealthDataModelType.EXERCISE.value -> {
                val sportData = arrayListOf<UserSportRecord>()
                mData.forEach {
                    JsonUtils.fromJson(it.value ?: "", UserSportRecord::class.java)?.let { beanIt ->
                        beanIt.sysStat = 1
                        sportData.add(beanIt)
                    }
                }
                SportRecordRepo.instance.insertDistinct(sportData)
            }
            ServerHealthDataModelType.SLEEP.value -> {
                val sleepData = arrayListOf<UserSleepInfo>()
                mData.forEach {
                    JsonUtils.fromJson(it.value ?: "", UserSleepInfo::class.java)?.let { beanIt ->
                        beanIt.sysStat = 1
                        sleepData.add(beanIt)
                    }
                }
                sleepMultiAdd2DB(sleepData)
            }
            else -> {
            }
        }

    }
}